package com.videoStream.video.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @Author: wwy
 * @Date: 2022/7/5 11:16
 */
@RestController
@RequestMapping
public class HlsUploadController {

    @Value("${upload.filePath}")
    private String path;

    /**
     * 保存m3u8与ts文件
     * @param request
     * @param virtualDirectory
     * @param fileName
     * @throws IOException
     */
    @PostMapping("upload/{virtualDirectory}/{fileName}")
    public void upload(HttpServletRequest request,@PathVariable("virtualDirectory") String virtualDirectory, @PathVariable("fileName") String fileName) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        FileWriter writer = new FileWriter(path+"\\"+virtualDirectory+"\\" + fileName);
        writer.writeFromStream(inputStream);
        IoUtil.close(inputStream);
    }

    /**
     * 删除ts文件
     * @param request
     * @param virtualDirectory
     * @param fileName
     * @throws IOException
     */
    @DeleteMapping("upload/{virtualDirectory}/{fileName}")
    public void delete(HttpServletRequest request,@PathVariable("virtualDirectory") String virtualDirectory, @PathVariable("fileName") String fileName) throws IOException {
        File file = new File(path+"\\"+virtualDirectory+"\\" + fileName);
        if(file.exists()){
            file.delete();
        }
    }
}
